-- Leviathan (c) v.v.balashoff
local Class = require('leviathan/Class')
local cyrillic = require('libs/cyrillic/cyrillic')

local TextShuffleSystem = Class:derive('UITextShuffleSystem')

function TextShuffleSystem:new(domain)
    self.name = 'TextShuffleSystem'
    self.domain = domain
end

function TextShuffleSystem:update(dt)
    local r = self.domain.components['TextShuffle']
    for _, c in pairs(r) do
        if c.enabled then
            -- local left = love.timer.getTime() - c.born
            if (love.timer.getTime() - c.born >= c.length) then
                c.enabled = false
                c.target.text = c.org -- restore text
                c.entity.domain.changed = true
                return
            end
            c.time = c.time + dt
            -- is it time to change?
            if c.time * 1000 > c.speed then
                c.time = 0
                local str = c.org
                local s = ''
                s = TextShuffleSystem:shuffleText(str)
                c.target.text = s
                c.entity.domain.changed = true
            end
        end
    end
end

function TextShuffleSystem:shuffleText(str)
    local len = cyrillic.len(str)
    local s = ''
    for _ = 1, len do
        local r = math.random(len)
        local ch = cyrillic.sub(str, r, r)
        s = s..ch
    end
    return s
end

return TextShuffleSystem
